package commonClass;

import java.io.IOException;
import java.util.Scanner;

public class RuntimeDemo {

	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException, InterruptedException {
		/**
		 * Runtime表示运行时操作类，是一个封装了jvm进程的类，每个jvm都对应着一个Runtime类的实例
		 * 此实例由jvm运行时为其实例化
		 */
		Runtime run=Runtime.getRuntime();
		System.out.println("JVM 最大内存量:"+run.maxMemory());
		System.out.println("JVM 空闲内存量:"+run.freeMemory());
		
		//产生多个String  占用内存
		String tempStr="hello";
		for(int i=0;i<1000;i++){
			tempStr+=" world ";
		}
		System.out.println("操作Stirng之后   JVM 空闲内存量:"+run.freeMemory());
		run.gc();//进行垃圾处理，释放空间
		System.out.println("垃圾回收之后   JVM 空闲内存量:"+run.freeMemory());
		
		execProcess(run, "notepad.exe");
	}

	/**
	 * 运行进程
	 * @param run
	 * @param processName
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void execProcess(Runtime run,String processName) throws IOException, InterruptedException{
		Process pro=null;
		pro=run.exec(processName);//运行进程
		Thread.sleep(5000);//沉睡5秒
		pro.destroy();//结束进程
	}
	/**
	 * 判断系统进程中是否存在某个进程
	 * @param processName
	 * @return
	 */
	public static boolean hasProcess(String processName){
		try {
			Process process = null;
			process = Runtime.getRuntime().exec("tasklist");//得到系统中的进程列表
			Scanner in = new Scanner(process.getInputStream());
			while (in.hasNextLine()) {
				String p = in.nextLine();
				if (p.contains(processName)) {
					return true;
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
